package com.moli.honjie.s002test.utils;

import android.app.Application;
import android.bluetooth.BluetoothGatt;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.moli.honjie.s002test.callback.BleConnectCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Timmy on 2018/3/25.
 */

public class BleUtils {

    private static final long SCAN_TIME = 5000;
    private static final String[] SCAN_DEVICE_NAME = {"S002"};

    private BleManager mBleManager;

    public static String UUID_SERVICE = "00000001-0000-1000-8000-00805f9b34fb";
    public static String UUID_NOTIFY = "00000003-0000-1000-8000-00805f9b34fb";
    public static String UUID_WRITE = "00000002-0000-1000-8000-00805f9b34fb";


    private static class BleUtilsHolder {
        private static final BleUtils bleUtils = new BleUtils();
    }

    public static BleUtils getInstance() {
        return BleUtilsHolder.bleUtils;
    }

    public void init(Application app) {
        mBleManager = BleManager.getInstance();
        mBleManager.init(app);
        mBleManager
                .enableLog(false)
                .setMaxConnectCount(1)
                .setOperateTimeout(500);
    }


    public void initScanRule() {
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                // .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
                //  只扫描指定广播名的设备，可选
                .setDeviceName(true, SCAN_DEVICE_NAME)
                // // 连接时的autoConnect参数，可选，默认false
                .setAutoConnect(false)
                // 扫描超时时间，可选，默认10秒
                .setScanTimeOut(SCAN_TIME)
                .build();

        BleManager.getInstance().initScanRule(scanRuleConfig);
    }

    /**
     * 判断蓝牙是否开启
     */
    public boolean isBlueEnable() {
        return mBleManager.isBlueEnable();
    }

    /**
     * 开启或者关闭蓝牙
     */
    public void enableBle() {
        mBleManager.enableBluetooth();
    }

    /**
     * 关闭蓝牙
     */
    public void disableBle() {
        mBleManager.disableBluetooth();
    }

    private List<BleDevice> mScanDevice = new ArrayList<>();

    public List<BleDevice> getScanDeviceList() {
        return mScanDevice;
    }

    /**
     * 扫描蓝牙设备
     */
    public void scanDevice(final BleScanCallback callback) {
        initScanRule();
        BleManager.getInstance().scan(callback);
    }


    private BleDevice mBleDevice;

    public void connectDevice(BleDevice bleDevice, final BleConnectCallback callback) {
        mBleDevice = bleDevice;
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                // 开始连接
            }

            @Override
            public void onConnectFail(BleException exception) {
                mBleDevice = null;
                // 连接失败
                if (callback != null) {
                    callback.onConnectFailure();
                }
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                // 连接成功
                if (callback != null) {
                    callback.onConnectSuccess();
                }
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                // 连接中断，isActiveDisConnected表示是否是主动调用了断开连接方法（UI线程）

            }
        });
    }


    // =================================== 发送数据 ===================================
    public void sendData(byte... bs) {
        byte[] dataToSend = DataUtils.getDataToSend(bs);

        BleManager.getInstance().write(mBleDevice, UUID_SERVICE, UUID_WRITE, dataToSend, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {

            }

            @Override
            public void onWriteFailure(BleException exception) {

            }
        });
    }

    public void openNotify(final BleNotifyCallback notifyCallback) {
        BleManager.getInstance().notify(
                mBleDevice,
                UUID_SERVICE,
                UUID_NOTIFY, notifyCallback);
    }

    public void closeNotify() {
        BleManager.getInstance().stopNotify(mBleDevice, UUID_SERVICE, UUID_NOTIFY);
    }


    /**
     * 判断设备当前是否在连接
     */
    public boolean deviceIsConnected() {
        if (mBleDevice != null) {
            return BleManager.getInstance().isConnected(mBleDevice);
        }
        return false;
    }

    /**
     * 断开所有设备
     */
    public void disconnectDevice() {
        if (deviceIsConnected()) {
            BleManager.getInstance().disconnect(mBleDevice);
        }
    }

    /**
     * 退出应用
     */
    public void onDestroy() {
        BleManager.getInstance().disconnectAllDevice();
        BleManager.getInstance().destroy();
    }
}
